#include "CStoryState.h"
#include "SGD Wrappers/CSGD_FModManager.h"
#include "SGD Wrappers/CSGD_TextureManager.h"
#include "SGD Wrappers/CSGD_DirectInput.h"
#include "CGame.h"
#include "CXInput.h"
#include "Mail System.h"
#include "CUnit.h"
#include "CObjectManager.h"
#include "CObjGenerator.h"
#include "CEventSystem.h"

CStoryState::CStoryState()
{
	Type(SUB);
	m_nBGImageID = CSGD_TextureManager::GetInstance()->LoadTexture("Resource/graphics/black.png");
	m_nImageID = CSGD_TextureManager::GetInstance()->LoadTexture("Resource/graphics/story_1.png");
	m_nBGMusicID = CSGD_FModManager::GetInstance()->LoadSound("Resource/sound/Batallia Downs.mp3");
	m_nScrollSpeed = 1;
}

CStoryState::~CStoryState()
{

}

CStoryState* CStoryState::GetInstance()
{
	static CStoryState instance;
	return &instance;
}

void CStoryState::Load(char* szFilename)
{
	static char buffer[128];
	sprintf_s(buffer,_countof(buffer),"Resource/graphics/%s", szFilename);
	m_nImageID = CSGD_TextureManager::GetInstance()->LoadTexture(buffer);
}

void CStoryState::Enter()
{
	m_nPosY = 600;

	ObjectGenerator<string, CBase>::GetInstance()->RegisterClassType<CUnit>("CUnit");
	MailSystem::GetInstance()->InitMessageSystem(CGame::GetInstance()->MessageProc);

	for(int i = 0; i < 100; ++i)
		MailSystem::GetInstance()->SendMail(new SpawnUnitMenu());


	MailSystem::GetInstance()->ReadMail();
}

void CStoryState::Exit()
{
	//MailSystem::GetInstance()->ShutdownMailSystem();
	//ObjectGenerator<string, CBase>::GetInstance()->UnregisterClassType("CUnit");
	CObjectManager::GetInstance()->Clear();
	//ObjectGenerator<string, CBase>::GetInstance()->ShutdownObjectFactory();
}

void CStoryState::Update(float fDelta)
{
	Input();
	m_nPosY -= m_nScrollSpeed;
	if(m_nPosY <= - 800)
		CGame::GetInstance()->PopState();

	MailSystem::GetInstance()->ReadMail();
	CEventSystem::GetInstance()->ProcessEvents();
	CObjectManager::GetInstance()->Update(fDelta);
}

bool CStoryState::Input()
{
	if(CSGD_DirectInput::GetInstance()->KeyDown(DIK_SPACE))
		m_nScrollSpeed = 5;
	else
		m_nScrollSpeed = 1;

	if(CXInput::GetInstance()->IsConnected())
	{
		if(CXInput::GetInstance()->PressButton() && XINPUT_GAMEPAD_B)
			m_nScrollSpeed = 5;
		else
			m_nScrollSpeed = 1;
	}

	if(CSGD_DirectInput::GetInstance()->KeyPressedEx(DIK_ESCAPE) 
		/*|| CSGD_DirectInput::GetInstance()->KeyPressedEx(DIK_RETURN)*/
		|| CXInput::GetInstance()->PressButton() && XINPUT_GAMEPAD_BACK)
		CGame::GetInstance()->PopState();
	return true;
}

void CStoryState::Render()
{
	CSGD_TextureManager::GetInstance()->Draw(m_nBGImageID, 0,0);

	CObjectManager::GetInstance()->Render();

	CSGD_TextureManager::GetInstance()->Draw(m_nImageID, 25, m_nPosY, .75f, .75f);
}